//
//  MallViewController.m
//  FlowerRainGround
//
//  Created by lanou on 16/4/25.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "MallViewController.h"
#import "headIvewModel.h"//头视图的模型
#import "JingListModel.h"
#import "JIngListTableViewCell.h"
#import "MallCollectionViewCell.h"
#import "MallSectionModel.h"
#import "MallCollectionReusableView.h"
@interface MallViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) headIvewModel *headModel;//头视图模型
@property (strong, nonatomic) IBOutlet UITableView *jingListTableVIew;//精选的tabelView
@property (nonatomic, strong) UICollectionView *collectionView;//商城的视图
@property (nonatomic, strong) UIScrollView *scrollerView;//整个滚动视图
@property (nonatomic, assign) NSInteger sorceTyep;
@property (nonatomic, strong) NSMutableArray *JingListArray;//精选的数组
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) NSMutableDictionary *mallDictionary;
@property (nonatomic, strong) NSMutableArray *mallMarray;
@property (nonatomic, strong) NSMutableArray *GoodsMarray;
@end

@implementation MallViewController

- (NSMutableArray *)JingListArray{
    if (!_JingListArray) {
        _JingListArray = [[NSMutableArray alloc] initWithCapacity:0];
        
    }
    return _JingListArray;
}

- (NSMutableDictionary *)mallDictionary{
    if (!_mallDictionary) {
        _mallDictionary = [[NSMutableDictionary alloc] initWithCapacity:0];
    }
    return _mallDictionary;
}

- (NSMutableArray *)mallMarray{
    if (!_mallMarray) {
        _mallMarray = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return _mallMarray;
}

- (NSMutableArray *)GoodsMarray{
    if (!_GoodsMarray) {
        _GoodsMarray = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return _GoodsMarray;
}




//头视图请求
- (void) requestData
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:@"http://ec.htxq.net/rest/htxq/index/carousel" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
        
        for (NSDictionary *dic1 in dic[@"result"]) {
            _headModel = [[headIvewModel alloc] init];
            [_headModel setValuesForKeysWithDictionary:dic1];
            
        }
        

       dispatch_async(dispatch_get_main_queue(), ^{
           [self creatHeadImage];
           
       });
 
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
}

//tableView的数据请求
- (void) requestDataForJinglistTable
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer =[AFHTTPResponseSerializer serializer ];
    [manager GET:JingList parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
        
        NSArray *array = dic[@"result"];
        for (NSDictionary *dic1 in array) {
            JingListModel *jinglist = [[JingListModel alloc] init];
            [jinglist setValuesForKeysWithDictionary:dic1];
            
            //商品
            for (NSDictionary *dic2 in dic1[@"skuList"]) {
                GoodsModel *good = [[GoodsModel alloc] init];
                [good setValuesForKeysWithDictionary:dic2];
                jinglist.goodsmodel = good;
            }
           
            [self.JingListArray addObject:jinglist];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.jingListTableVIew reloadData];
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
     
}


//商城的collectionView
- (void) requestMallData
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:Mall parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
        NSArray *array = dic[@"result"];
        
        for (NSDictionary  *dic1 in  array  ) {
            
            //分区
            MallSectionModel *mallSectonModel = [[MallSectionModel alloc] init];
            [mallSectonModel setValuesForKeysWithDictionary:dic1];
            
            
            //商城的内容
            for (NSDictionary *dic2 in dic1[@"childrenList"]) {
                
                    MallModel *model = [[MallModel alloc] init];
                    [model setValuesForKeysWithDictionary:dic2[@"pGoods"]];
                    [self.GoodsMarray addObject:model];
                
                
                    mallSectonModel.mallModel = model;
                
                
                    [self.mallMarray addObject:mallSectonModel];
                
            }
            
            //分区表示
            [self.mallDictionary setObject:self.mallMarray forKey:dic1[@"fnName"]];
            
            
        }
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView reloadData];
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
}









- (void)viewDidLoad {
    [super viewDidLoad];
    [self requestData];
    
    self.sorceTyep = 1;
    self.navigationController.navigationBar.translucent = NO;
    [self creatTableView];
    [self requestDataForJinglistTable];
    
    [self requestMallData];

    
    // Do any additional setup after loading the view from its nib.
}



- (void)creatHeadImage {
    
    //创建scrollerView
    _scrollerView = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _scrollerView.contentSize = CGSizeMake(kWidth, self.jingListTableVIew.frame.size.height);
    _scrollerView.contentOffset = CGPointMake(0, 0);
    _scrollerView.showsHorizontalScrollIndicator = YES;
    [self.view addSubview:_scrollerView];
    
    
    _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 260)];
    _headerView.backgroundColor = [UIColor yellowColor];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 200)];
    [imageView sd_setImageWithURL:[NSURL URLWithString:self.headModel.fnImageUrl]];
    [_headerView addSubview:imageView];
    
    
    UIView *choseheadView = [[UIView alloc] initWithFrame:CGRectMake(0, imageView.frame.size.height, kWidth, 60)];
    UIButton *jingListButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [jingListButton setTitle:@"精选" forState:UIControlStateNormal];
    jingListButton.frame = CGRectMake(60, 10, (kWidth - 180) / 2, 40);
    [choseheadView addSubview:jingListButton];
    jingListButton.block = ^(){
    
        [self creatTableView];//创建tableView
    };
    
    UIButton *mallButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [mallButton setTitle:@"商城" forState:UIControlStateNormal];
    mallButton.frame = CGRectMake(120 + (kWidth - 180) / 2 , 10, (kWidth - 180) / 2, 40);
    mallButton.block = ^(){
        [self creatCollectView];
    };
    [choseheadView addSubview:mallButton];
    [choseheadView addSubview:mallButton];
    
    
    [_headerView addSubview:choseheadView];
    [self.scrollerView addSubview:_headerView];
    
 
}

//点击精选创建tableView
- (void) creatTableView{
    
     self.jingListTableVIew = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight) style:(UITableViewStylePlain)];
     self.jingListTableVIew.delegate =self;
     self.jingListTableVIew.dataSource = self;
    self.jingListTableVIew.tableHeaderView = self.headerView;
    
    //注册cell
    [self.jingListTableVIew registerNib:[UINib nibWithNibName:@"JIngListTableViewCell" bundle:nil] forCellReuseIdentifier:@"reuse"];
     [self.scrollerView addSubview:self.jingListTableVIew];
    
}

#pragma mark-----tableViewDelegate--------
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.JingListArray.count;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 240;
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *string = @"reuse";
    JingListModel *model = self.JingListArray[indexPath.row];
    JIngListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
    if (!cell) {
        cell = [[JIngListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string];
    }
    cell.jingModel = model;
    return cell;
}



#pragma mark-----collectorDelegate--------
- (void) creatCollectView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.headerReferenceSize = CGSizeMake(kWidth, 60);
    flowLayout.minimumInteritemSpacing = 10;
    flowLayout.minimumLineSpacing = 10;
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    flowLayout.itemSize = CGSizeMake((kWidth - 30)/2, 200);
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight) collectionViewLayout:flowLayout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    //注册cell
    [self.collectionView registerClass:[MallCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reuse"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"MallCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"reuse"];
    
    [self.scrollerView addSubview:self.collectionView];
}

//分区的个数
- (NSInteger) numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    //分区的个数
    return self.mallDictionary.count;
}

//每个分区的item
- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
     NSLog(@"qqqqqq%@", [self.mallDictionary objectForKey:self.mallDictionary.allKeys[section]]);
    return [self.mallDictionary[self.mallDictionary.allKeys[section]] count];
  
}


//cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *string = @"reuse";
    MallCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:string forIndexPath:indexPath];
    
    
    MallSectionModel *model = self.mallDictionary[self.mallDictionary.allKeys[indexPath.section]][indexPath.row];
    cell.backgroundColor = [UIColor yellowColor];
    
    [cell.backgroundImage sd_setImageWithURL:[NSURL URLWithString:model.mallModel.fnAttachment]];
    cell.fnEnNameLabel.text = model.mallModel.fnEnName;
    cell.fnNameLabel.text = model.mallModel.fnName;
    cell.priceLabel.text = [NSString stringWithFormat:@"%ld", model.mallModel.fnMarketPrice];

    return cell;
}


- (UICollectionReusableView *) collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    MallCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reuse" forIndexPath:indexPath];
    view.backgroundColor = [UIColor whiteColor];

    view.headerlabel.text = self.mallDictionary.allKeys[indexPath.section];
    return view;
    
}









- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
